﻿using System.Web.Mvc;

namespace CodeContrib.Web.Mvc
{
	public class PagingBinder : IModelBinder
	{
		private static string _pageNumberKey;
		private static string _pageSizeKey;

		public static string PageNumberKey
		{
			get
			{
				if (string.IsNullOrEmpty(_pageNumberKey))
				{
					_pageNumberKey = "page";
				}

				return _pageNumberKey;
			}
			set { _pageNumberKey = value; }
		}

		public static string PageSizeKey
		{
			get
			{
				if (string.IsNullOrEmpty(_pageSizeKey))
				{
					_pageSizeKey = "size";
				}

				return _pageSizeKey;
			}
			set { _pageSizeKey = value; }
		}

		public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
		{
			Guard.NotNull(bindingContext, "bindingContext");

			var pageNumber = bindingContext.GetValueOrDefault(PageNumberKey, 1);
			var pageSize = bindingContext.GetValueOrDefault(PageSizeKey, 10);

			return new Paging(pageNumber, pageSize);
		}
	}
}